package com.zzw.controller;

import com.zzw.bean.Msg;
import com.zzw.bean.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Shiro控制器
 * 用于提供Shiro相关的操作API
 * @author 赵志伟
 * @version 1.0
 */
@Controller
@RequestMapping("/shiro")
public class ShiroController {

    @Autowired
    private EhCacheManager cacheManager;

    /**
     * 清除当前用户的权限缓存
     * 当角色权限变更后调用，使权限变更立即生效
     * @return 操作结果
     */
    @GetMapping("/clearCache")
    @ResponseBody
    public Msg clearCache() {
        try {
            // 获取当前登录的用户
            Subject subject = SecurityUtils.getSubject();
            if (!subject.isAuthenticated()) {
                return Msg.fail().setMsg("用户未登录");
            }

            // 从Subject中获取用户对象
            SysUser user = (SysUser) subject.getPrincipal();

            // 清除认证缓存
            Cache<Object, Object> authenticationCache = cacheManager.getCache("authenticationCache");
            if (authenticationCache != null) {
                authenticationCache.remove(user.getUsername());
            }

            // 清除授权缓存
            Cache<Object, Object> authorizationCache = cacheManager.getCache("authorizationCache");
            if (authorizationCache != null) {
                authorizationCache.remove(user.getUsername());
            }

            // 强制刷新授权信息
            subject.runAs(subject.getPrincipals());

            return Msg.success().setMsg("权限缓存已清除");
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail().setMsg("清除缓存失败: " + e.getMessage());
        }
    }
}
